// packageA/pages/equipmentScreenList/equipmentScreenList.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //筛选
    showScreen:false,
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //搜索关键词
    searchValue:'',
    //分类列表
    classifyList:[],
    //品牌列表
    brandMap:[],
    //筛选条件
    condition:{},
    //清洁宽度范围列表
    clearWidthList:[{
      id:1,
      min:0,
      max:1
    },{
      id:2,
      min:1,
      max:5
    },{
      id:3,
      min:5,
      max:10
    }],
    //路面宽度范围列表
    widthList:[{
      id:1,
      min:0,
      max:1
    },{
      id:2,
      min:1,
      max:5
    },{
      id:3,
      min:5,
      max:10
    }],
    //地面数据
    floorList:[],
    //污染源数据
    polluteList:[],
    //价格id
    priceIds:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取分类名称
    this.getClassifyList();

    //获取品牌列表
    this.getBrandList();

    //查询字典-地面
    this.getFloors();

    //查询字典-污染源
    this.getPollute();

    //列表数据
    this.getList();
  },

  //列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let dataObj={
        //禁用的不查
        validState: {
            '!=': 2
        },
        selectFields: ['id','name','categoryId','imgUrl','sku','brandId','clWidth','eqWidth','grounds','splList','category'],
        page: {
        page: this.data.page,
        pageSize: 10
      },
      nbl:Base64.encode(util.timeFormatDay(new Date()))
    }

    //搜索设备型号
    if(this.data.searchValue){
      dataObj.name='%'+this.data.searchValue+'%';
    }

    let condition=this.data.condition;

    //筛选-清洁宽度
    if(condition.bigClearWidth){
      dataObj['clWidth.value']={
        '>=':condition.minClearWidth*1000,
        '<=':condition.bigClearWidth*1000
      }
    }

    //筛选-路面宽度
    if(condition.bigWidth){
      dataObj['eqWidth.value']={
        '>=':condition.minWidth*1000,
        '<=':condition.bigWidth*1000
      }
    }

    //筛选-地面
    if(condition.floor && condition.floor.length){
      dataObj.grounds=condition.floor;
    }

    //筛选-污染源
    if(condition.pollute && condition.pollute.length){
      dataObj.splList=condition.pollute;
    }

    let param = {
      isAuth: false,
      className: 'spu',
      data: dataObj
    }

    CommonService.goFindList(param).then(res => {  
      Toast.clear();
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        let arr=[];
        let brandMap=this.data.brandMap;

        result.forEach(item => {
          //处理分类名称
          if(item.categoryId && item.categoryId.length){
            let val=item.categoryId;
            if(val.length != 3){
              val.unshift(1)
            }
            let name = this.getCategoriesNameInMethods(this.data.classifyList, val, 1, '');
            item.self_category=name.substring(0, name.length - 1);
          }else{
            item.self_category='暂无分类信息'
          }         

          //获取品牌名称
          if(item.brandId){
            item.brandName=brandMap.get(item.brandId);
          }

          //处理配置价格
          if(item.sku && item.sku.length){
            let idx=0;
            item.sku.forEach((o,i)=> {
              if(o.defChecked){
                idx=i;
              }
            });

            arr.push(item.sku[idx].id);
            item.skuId=item.sku[idx].id;
            item.showSku=item.sku[idx];
          } 
        });

        console.log('设备列表');
        console.log(result);

        this.setData({
          list: this.data.list.concat(result),
          priceIds: this.data.priceIds.concat(arr)
        })

        //查询价格
        this.getPrice();
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
    })
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value,
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },

  //显示筛选
  onShowScreen(){
    this.setData({
			showScreen: true
    })
  },

  //隐藏筛选
  onCloseScreen(){
    this.setData({
      showScreen: false
    })
  },

  //确认筛选
  onConfirm(e){
    let condition=this.data.condition;

    //最小值不能大于最大值
    let flag1=true,flag2=true;
    if(condition.bigClearWidth!=null && condition.minClearWidth!=null){
      if(condition.bigClearWidth < condition.minClearWidth){
        flag1=false;
      }
    }
    if(condition.bigWidth!=null && condition.minWidth!=null){
      if(condition.bigWidth < condition.minWidth){
        flag2=false;
      }
    }

    if(flag1 && flag2){
      this.onCloseScreen();
      this.refreshListAndPage();
    }else{
      Toast.fail('最小值不能大于最大值');
    }
  },

  //跳转详情
  goToDetail(e){
    let detail=e.currentTarget.dataset.detail;
    let paramObj={
      id: detail.id,
      categoryName: detail.self_category ? detail.self_category : '暂无分类信息',
      brandName: detail.brandName ? detail.brandName : '暂无品牌信息'
    }
    wx.navigateTo({
      url: "/packageA/pages/equipmentDetail/equipmentDetail?paramObj="+JSON.stringify(paramObj)
    })
  },

  //清洁宽度最小值
  onGetMinClearWidth(e) {
    let minClearWidth='condition.minClearWidth';
    this.setData({
      [minClearWidth]:e.detail.value
    })
  },

  //清洁宽度最大值
  onGetBigClearWidth(e) {
    let bigClearWidth='condition.bigClearWidth';
    this.setData({
      [bigClearWidth]:e.detail.value
    })
  },

  //选择清洁宽度
  onGetClearWidth(e){
    let detail=e.currentTarget.dataset.detail;

    let list=this.data.clearWidthList;
    list.forEach(item => {
      item.current=false;
		  if (item.id==detail.id){
        item.current=true;
		  }
    });

    let minClearWidth='condition.minClearWidth';
    let bigClearWidth='condition.bigClearWidth';
    this.setData({
      [minClearWidth]:detail.min,
      [bigClearWidth]:detail.max,
      clearWidthList:list
    })
  },

  //清洁次数
  onGetClearCount(e){
    let clearCount='condition.clearCount';
    this.setData({
      [clearCount]:e.detail.value
    })
  },

  //路面宽度最小值
  onGetMinWidth(e) {
    let minWidth='condition.minWidth';
    this.setData({
      [minWidth]:e.detail.value
    })
  },

  //路面宽度最大值
  onGetBigWidth(e) {
    let bigWidth='condition.bigWidth';
    this.setData({
      [bigWidth]:e.detail.value
    })
  },

  //点击选择路面宽度
  onGetWidth(e){
    let detail=e.currentTarget.dataset.detail;

    let list=this.data.widthList;
    list.forEach(item => {
      item.current=false;
		  if (item.id==detail.id){
        item.current=true;
		  }
    });

    let minWidth='condition.minWidth';
    let bigWidth='condition.bigWidth';
    this.setData({
      [minWidth]:detail.min,
      [bigWidth]:detail.max,
      widthList:list
    })
  },

  //查询字典-地面
  getFloors(){
    let param1 = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'floors',
        selectFields: ['id','name','url'],
        nbl:Base64.encode(util.timeFormatDay(new Date()))
      }
    }

    CommonService.goFindList(param1).then(res=>{  
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            id:item.id,
            name:item.name,
            url:item.url
          });
        });
        this.setData({
          floorList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //点击选择地面
  onGetFloor(e){
    let detail=e.currentTarget.dataset.detail;

    let list=this.data.floorList;
    list.forEach(item => {
		  if (item.id==detail.id){
        item.current=!item.current;
		  }
    });

    let ids=[];
    list.forEach(item => {
		  if (item.current){
        ids.push(item.id);
		  }
    });

    let floor='condition.floor';
    this.setData({
      [floor]:ids,
      floorList:list
    })
  },

  //查询字典-污染源
  getPollute(){
    let param1 = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'sourcePollution',
        selectFields: ['id','name'],
        nbl:Base64.encode(util.timeFormatDay(new Date()))
      }
    }

    CommonService.goFindList(param1).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            id:item.id,
            name:item.name
          });
        });
        this.setData({
          polluteList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //点击选择污染源
  onGetPollute(e){
    let detail=e.currentTarget.dataset.detail;

    let list=this.data.polluteList;
    list.forEach(item => {
		  if (item.id==detail.id){
        item.current=!item.current;
		  }
    });

    let ids=[];
    list.forEach(item => {
		  if (item.current){
        ids.push(item.id);
		  }
    });

    let pollute='condition.pollute';
    this.setData({
      [pollute]:ids,
      polluteList:list
    })
  },

  //重置
  onReset(){
    let clearWidthList=this.data.clearWidthList,
        widthList=this.data.widthList,
        floorList=this.data.floorList,
        polluteList=this.data.polluteList;

    this.listNotSelected(clearWidthList,'clearWidthList');
    this.listNotSelected(widthList,'widthList');
    this.listNotSelected(floorList,'floorList');
    this.listNotSelected(polluteList,'polluteList');

    this.setData({
      condition:{}
    })

    this.refreshListAndPage();
  },

  //批量处理列表
  listNotSelected(list,str){
    list.forEach(item => {
      item.current=false;
    });

    this.setData({
      [str]:list
    })
  },

  //查询价格
  getPrice(){
    let param = {
      isAuth: false,
      className: 'pricingStrategy',
      data: {
        skuId: this.data.priceIds,
        type: 3,
        searchAll: true,
        selectFields: ['id', 'deposit', 'leaseTerm', 'rangeUnit','leasePrice','skuId'],
        nbl:Base64.encode(util.timeFormatDay(new Date()))
      }
    }

    CommonService.goFindList(param).then(res=>{
      if (res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        let list=this.data.list;
        for(let i=0;i<list.length;i++){
          list[i].priceArr=[];
          result.forEach(item => {
            if(item.skuId==list[i].skuId){
              list[i].priceArr.push(item);
            }
          });
        }
        this.setData({
          list:list
        })

        console.log('带价格设备列表');
        console.log(list);
      }
    }).catch((error) => {
    })
  },

  //获取品牌列表
  getBrandList(){
    let param = {
      isAuth: false,
      className: 'brand',
      data: {
        searchAll: true, 
        selectFields: ['id', 'name'],
        nbl:Base64.encode(util.timeFormatDay(new Date()))
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let map=new Map();

        result.forEach(item => {
          map.set(item.id,item.name);
        });

        this.setData({ 
          brandMap: map
        }) 
      }
    }).catch((error) => {
    })
  }, 
  
  //获取分类名称列表
  getClassifyList(){
    CommonService.getCategoryTree().then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        if (result.length == 1) {
          this.data.classifyList = result[0].children;
        }else {
          this.data.classifyList = result;
        }
      } 
    }).catch((error) => {
    })
  },
  
  //获取分类名称
  getCategoriesNameInMethods(source, val, index, name) {
    if (source) {
      for (let i = 0; i < source.length; i++) {
        if (source[i].id === val[index]) {
          name += source[i].name + '/';
          return this.getCategoriesNameInMethods(source[i].children, val, ++index, name);
        }
      }
    }
    return name;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})
